/**
\ * Copyright &copy; 2012-2014 <a href="http://www.zhiqone.com">http://www.zhiqone.com</a> All rights reserved.
 */
package com.zcm.modules.center.web.front;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zcm.common.utils.StringUtils;
import com.zcm.common.web.BaseController;
import com.zcm.modules.center.entity.CenterUser;
import com.zcm.modules.center.service.CenterUserService;
import com.zcm.modules.center.utils.NoticeUtils;
import com.zcm.modules.cms.utils.CmsUtils;
import com.zcm.modules.sys.service.SystemService;
import org.activiti.engine.impl.util.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 项目前端展示Controller
 * @author liangstc
 * @version 2016-03-03
 */
@Controller
@RequestMapping(value = "${frontPath}")
public class CenterFrontController extends BaseController {
	@Autowired
	private CenterUserService centerUserService;

	/**
	 * 验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "smgRandom")
	@ResponseBody
	public Map<String, Object> smgRandom(HttpServletRequest request){
		Map<String, Object> result=new HashMap<String, Object>();
		String mobile = request.getParameter("mobile");
		Random random = new Random();
		String code="";
		for(int i=0;i<6;i++){
			code+=random.nextInt(10);
		}
		HttpSession session = request.getSession();
		session.setAttribute("code", code);
		session.setMaxInactiveInterval(5*60);//有效期5分钟？

		try {
			Map<String,String> params = new HashMap<String, String>();
			params.put("code",code);
			NoticeUtils.sendSms(params,mobile);
			result.put("message", "短信发送成功！");
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("message", "短信发送失败，请检查输入的电话号码是否有误！");
			result.put("success", false);
		}
		return result;
	}

	/**
	 * 验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "smgForgetPasswd")
	@ResponseBody
	public Map<String, Object> smgForgetPasswd(HttpServletRequest request){
		Map<String, Object> result=new HashMap<String, Object>();
		String mobile = request.getParameter("mobile");
		Random random = new Random();
		String code="";
		for(int i=0;i<6;i++){
			code+=random.nextInt(10);
		}
		HttpSession session = request.getSession();
		session.setAttribute("coder", code);
		session.setAttribute("mobile", mobile);
		session.setMaxInactiveInterval(5*60);//有效期5分钟？

		try {
			Map<String,String> params = new HashMap<String, String>();
			params.put("code",code);
			NoticeUtils.forgetPasswdMsg(params,mobile);
			result.put("message", "短信发送成功！");
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("message", "短信发送失败，请检查输入的电话号码是否有误！");
			result.put("success", false);
		}
		return result;
	}

	//注册
	@RequestMapping(value = "register",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> register(@RequestParam(value = "loginName") String loginName,@RequestParam(value = "password") String passWord,@RequestParam(value = "mobile") String mobile,HttpServletRequest request) throws JSONException {
		Map<String, Object> map=new HashMap<String, Object>();
		HttpSession session = request.getSession();
		CenterUser centerUser = centerUserService.getUserByLoginName(loginName);
		if(null!=centerUser) {
			map.put("success", false);
			map.put("message", "用户已存在");
			return map;
		}

		String code = (String) session.getAttribute("code");
		String smgcode = request.getParameter("smgcode");

		if(StringUtils.isEmpty(code)){
			map.put("message","未获取短信验证码或者短信验证码已过期，请点击获取短信验证码按钮！");
			map.put("success", false);
			return map;
		}

		if(StringUtils.isEmpty(smgcode)){
			map.put("message","请填写短信验证码！");
			map.put("success", false);
			return map;
		}

		if(!code.equals(smgcode)){
			map.put("message","短信验证码有误！");
			map.put("success", false);
			return map;
		}


		CenterUser user = new CenterUser();
		user.setLoginName(loginName);
		user.setPassword(SystemService.entryptPassword(passWord));
		user.setMobile(mobile);
		user.setAuditFlag("1");
		centerUserService.save(user);
		if (user.getId() !=null ) {
			map.put("success", true);
			map.put("message", "注册成功！");
			return map;
		} else {
			map.put("success", true);
			map.put("message", "注册失败！");
			return map;
		}
	}


    /**
     * 验证手机号
     * @param mobile
     * @return
     */
    @RequestMapping(value = "validateMobile")
    @ResponseBody
    public Map<String, Object> validateMobile(@RequestParam String mobile){
        Map<String, Object> result=new HashMap<String, Object>();
        CenterUser res = centerUserService.getUserByMobile(mobile);
        result.put("success", res == null);
        return result;
    }

	// 存在手机号则返回true
    @RequestMapping(value = "existsMobile")
    @ResponseBody
    public String existsMobile(@RequestParam String mobile,HttpServletRequest request, HttpServletResponse response){
        CenterUser res = centerUserService.getUserByMobile(mobile);
        return res!=null?"true":"false";
    }

    // 不存在手机号则返回true
    @RequestMapping(value = "notExistsMobile")
    @ResponseBody
    public String notExistsMobile(@RequestParam String mobile,HttpServletRequest request, HttpServletResponse response){
        CenterUser res = centerUserService.getUserByMobile(mobile);
        return res==null?"true":"false";
    }


    /**
     * 判断用户名是否存在
     * @param loginName
     * @return
     */

    // 用户名校验
    @RequestMapping(value = "validateLoginName")
    @ResponseBody
    public Map<String, Object> validateLoginName(@RequestParam String loginName){
        Map<String, Object> result=new HashMap<String, Object>();
        result.put("success", null==centerUserService.getUserByLoginName(loginName));
        return result;
    }

	// 跳转至注册页面
    @RequestMapping(value ="register", method = RequestMethod.GET)
    public String toRegister( Model model){
        model.addAttribute("site", CmsUtils.getSite(null));
        model.addAttribute("isIndex", true);
        model.addAttribute(new CenterUser());
        return "modules/center/front/centerRegister";
    }


    // 忘记密码 短信验证码验证
    @RequestMapping(value ="validMobileForget")
    @ResponseBody
    public String validMobileForget(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("coder");
        String smgcode = request.getParameter("coder");
        if(StringUtils.isEmpty(code)){
            return "false";
        }

        if(StringUtils.isEmpty(smgcode)){
            return "false";
        }

        if(!code.equals(smgcode)){
            return "false";
        }
        return "true";
    }

    // 跳转至忘记密码
    @RequestMapping(value = "forgetPwd" ,method = RequestMethod.GET)
    public String toForgetPwd(Model model) throws JSONException {
        model.addAttribute("site", CmsUtils.getSite(null));
        model.addAttribute("isIndex", true);
        model.addAttribute(new CenterUser());
        return "modules/center/front/forgetPasswd";
    }

	// 忘记密码表单提交
	@RequestMapping(value = "forgetPwd" ,method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> interForgetPwd(HttpServletRequest request) throws JSONException {
		Map<String, Object> map=new HashMap<String, Object>();
		HttpSession session = request.getSession();
		String newPassWord = request.getParameter("password");
		String mobile = (String) session.getAttribute("mobile");
		if(StringUtils.isEmpty(mobile)){
			map.put("message","获取验证码的手机号已过期，请重新获取短信验证码！");
			map.put("success", false);
			return map;
		}
		if(StringUtils.isEmpty(newPassWord))
		{
			map.put("message","新密码为空");
			map.put("success", false);
			return map;
		}
		String password = SystemService.entryptPassword(newPassWord);
		CenterUser centerUser = centerUserService.getUserByMobile(mobile);

		centerUser.setPassword(password);
		centerUserService.save(centerUser);
			map.put("message", "密码设置成功!请重新登录!");
			map.put("success", true);
		return map;
	}
}